<?php

namespace app\system\controller;

use think\Controller;
use app\system\model\SysConfigModel;
use app\system\model\SysMenuModel;
use app\system\model\SysRoleModel;
use think\facade\Request;
use app\system\model\SysAdminModel;

class MainFrame extends Controller
{

    protected  function initialize()
    {
        $this->checkLogin(); // 检查登陆
        $this->checkAuth();  // 检查权限
    }

    /**
     * 检查登陆
     */
    protected function checkLogin()
    {
        if (session("admin_user") == null) {
            $url = url('system/LoginSystem/doLogin');
            echo "<script type='text/javascript'>";
            echo "top.location.href = '" . $url . "';";
            echo "</script>";
            exit;
        }
    }

    /**
     * 检查权限
     */
    protected function checkAuth()
    {
        $sysMenuModel = new SysMenuModel();
        $sysRoleModel = new SysRoleModel();

        $role_id = session("admin_user")["role_id"];
        $role = $sysRoleModel->getRoleById($role_id);
        $auth_menu_id_arr = explode(",", $role["auth"]);
        $menu = $sysMenuModel->all($auth_menu_id_arr);

        $urlArr = [];
        foreach ($menu as $key => $val) {
            $urlArr[] = $val["mca_url"];
        }

        $nowUrl = Request::module() . "/" . Request::controller() . "/" . Request::action(true);

        $outArr = [
            "system/MainFrame/showIndex",   //后台首页
            "system/MainFrame/welcome",     //欢迎页
            "system/MainFrame/outLogin",    //登陆页
            "system/MainFrame/updPwd",      //修改密码
        ];

        // 阻止访问
        if (!in_array($nowUrl, $outArr)) {
            if (!in_array($nowUrl, $urlArr)) {
                if (Request::isAjax()) {
                    $this->retJson(["code" => 101, "msg" => "You not authority access!"]);
                    exit;
                } else {
                    exit("You not authority access!");
                }
            }
        }
    }

    // 封装json
    protected function retJson($data, $options = 0, $exit = true)
    {
        // 设置默认的JSON选项
        $defaultOptions = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
        $options = $options | $defaultOptions;

        // 使用json_encode编码数据
        $jsonString = json_encode($data, $options);

        // 检查json_encode是否成功
        if ($jsonString === false) {
            // 获取错误信息
            $error = json_last_error_msg();
            // 在实际应用中，可能会记录错误或者抛出异常
            // 这里仅打印错误信息
            echo $error;
            return;
        }

        // 设置HTTP响应头部，表明内容类型为JSON
        header('Content-Type: application/json; charset=utf-8');

        // 如果需要终止脚本执行，则直接输出JSON字符串并退出
        if ($exit) {
            exit($jsonString);
        }

        // 如果不需要终止脚本执行，则返回JSON字符串
        return $jsonString;
    }

    /**
     * 后台首页
     */
    public function showIndex(SysConfigModel $sysConfigModel, SysMenuModel $sysMenuModel, SysRoleModel $sysRoleModel)
    {
        $systemName = $sysConfigModel->getConfigValue("systemName");    // 系统名称
        $menuList = $sysMenuModel->getMenuList();   // 取菜单
        $menuList = $this->buildTree($menuList);    // 构建树形结构
        $role_id = session("admin_user")["role_id"];
        $role = $sysRoleModel->getRoleById($role_id);
        $auth_menu_id_arr = explode(",", $role["auth"]);
        $this->assign([
            "systemName" => $systemName,
            "menuList" => $menuList,
            "auth_menu_id_arr" => $auth_menu_id_arr
        ]);
        return $this->fetch();
    }

    /**
     * 构建树形
     */
    protected function buildTree($elements, $parentId = 0)
    {
        $branch = array();
        foreach ($elements as $element) {
            if ($element['pid'] == $parentId) {
                $children = $this->buildTree($elements, $element['menu_id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }

    /**
     * 欢迎页
     */
    public function welcome(SysConfigModel $sysConfigModel, SysRoleModel $sysRoleModel)
    {
        $systemInfo = [
            "domain" => $_SERVER['HTTP_HOST'],  // 服务器域名
            "osInfo" => php_uname('s'),         // 操作系统
            "phpVersion" => phpversion(),       // php版本
            "phpSapi" => php_sapi_name(),       // php运行方式
            "uploadMaxSize" => ini_get('upload_max_filesize'), // 上传限制
            "currentMaxExecutionTime" => ini_get('max_execution_time'), // 脚本最大执行时间
        ];

        $devTeam = [
            "banqInfo" => $sysConfigModel->getConfigValue("banqInfo"),       // 版权信息
            "coder" => $sysConfigModel->getConfigValue("coder"),    // 开发者
            "footerInfo" => $sysConfigModel->getConfigValue("footerInfo")    // 感谢信息
        ];

        $role = $sysRoleModel->getRoleById(session("admin_user")["role_id"]);
        $this->assign([
            "role" => $role,
            "systemInfo" => $systemInfo,
            "devTeam" => $devTeam
        ]);
        return $this->fetch();
    }

    /**
     * 登陆退出
     */
    public function outLogin()
    {
        session(null);
        $this->redirect("system/LoginSystem/doLogin");
    }

    /**
     * 修改密码
     */
    public function updPwd(SysAdminModel $sysAdminModel)
    {
        if (Request::isAjax()) {
            $oldPwd = input("old_pwd");
            $newPwd = input("new_pwd");
            if (md5($oldPwd) != session("admin_user")["pwd"]) {
                return json(["code" => 1, "msg" => "旧密码错误!err:1"]);
            }
            $updResult = $sysAdminModel->updUserData(["pwd" => md5($newPwd)], session("admin_user")["admin_id"]);
            // dump($sysAdminModel->getLastSql());die;
            if ($updResult != false) {
                return json(["code" => 1, "msg" => "修改成功"]);
            }
        } else {
            return $this->fetch();
        }
    }
}
